<template>
    <div class="user-list-wrapper">
        <el-card>
            <!-- 筛选表单 -->
            <el-form :inline="true" :model="queryParams" class="mb-2">
                <el-form-item label="用户名">
                    <el-input v-model="queryParams.username" placeholder="精确查询用户名" clearable size="small"
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="用户类型">
                    <el-select v-model="queryParams.user_type" clearable placeholder="全部" size="small"
                        @change="handleQuery">
                        <el-option label="普通用户" value="regular" />
                        <el-option label="临时会员" value="temporary_member" />
                        <el-option label="体验会员" value="trial_member" />
                        <el-option label="续费会员" value="renewal_member" />
                    </el-select>
                </el-form-item>
                <el-form-item label="国家">
                    <el-select v-model="queryParams.country" filterable clearable placeholder="国家" size="small"
                        @change="handleQuery">
                        <el-option v-for="item in countryOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="城市">
                    <el-input v-model="queryParams.city" placeholder="城市" clearable size="small"
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="性别">
                    <el-select v-model="queryParams.gender" clearable placeholder="全部" size="small"
                        @change="handleQuery">
                        <el-option label="男" value="0" />
                        <el-option label="女" value="1" />
                        <el-option label="保密" value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="注册时间">
                    <el-date-picker v-model="value1" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                        :start-placeholder="'开始日期'" :end-placeholder="'结束日期'" @change="timeChange">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="small" icon="el-icon-search" @click="handleQuery">查询</el-button>
                    <el-button type="default" size="small" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>

            <!-- 用户列表 -->
            <el-table :data="userList" border v-loading="loading" style="width: 100%;">
                <el-table-column prop="username" label="用户名" align="center" show-overflow-tooltip />
                <el-table-column prop="user_type" label="用户类型" align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.user_type === 'regular'" type="info">普通</el-tag>
                        <el-tag v-else-if="scope.row.user_type === 'temporary_member'" type="warning">临时会员</el-tag>
                        <el-tag v-else-if="scope.row.user_type === 'trial_member'" type="success">体验会员</el-tag>
                        <el-tag v-else-if="scope.row.user_type === 'renewal_member'" type="primary">续费会员</el-tag>
                        <el-tag v-else type="info">{{ scope.row.user_type }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="subscription_expiry_date" label="过期时间" align="center" />
                <el-table-column prop="country" label="国家" align="center" show-overflow-tooltip />
                <el-table-column prop="city" label="城市" align="center" show-overflow-tooltip />
                <el-table-column prop="gender" label="性别" align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.gender === 0">男</span>
                        <span v-else-if="scope.row.gender === 1">女</span>
                        <span v-else>保密</span>
                    </template>
                </el-table-column>
                <el-table-column prop="registration_time" label="注册时间" align="center" />
                <el-table-column prop="invited_count" label="邀请人数" align="center" />
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="showDetail(scope.row)" type="text">详情</el-button>
                        <el-button size="mini" type="text" @click="showUserAffirmations(scope.row)">
                            自定义肯定语（{{ scope.row.userAffirmationsCount || 0 }}）
                        </el-button>
                        <el-button size="mini" type="text" @click="showFavoritesAffirmations(scope.row)">
                            收藏肯定语（{{ scope.row.favoriteAffirmationsCount || 0 }}）
                        </el-button>

                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryParams.page" :page-sizes="[10, 20, 50, 100]" :page-size="queryParams.size"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>

        <!-- 用户详情弹窗 -->
        <el-dialog :visible.sync="showDialog" width="1000px" title="用户详情">
            <el-form label-width="160px" size="small">
                <!-- 基本信息 -->
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="用户ID">
                            <el-input v-model="currentUser.user_id" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="用户名">
                            <el-input v-model="currentUser.username" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="头像">
                            <el-input v-model="currentUser.avatar_url" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="认证类型">
                            <el-input v-model="currentUser.auth_type" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="用户类型">
                            <el-input v-model="currentUser.user_type" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="微信标识">
                            <el-input v-model="currentUser.wechat_identifier" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="苹果标识">
                            <el-input v-model="currentUser.apple_identifier" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 会员信息 -->
                <el-divider>会员信息</el-divider>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="当前订阅产品ID">
                            <el-input v-model="currentUser.current_product_id" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="原始交易ID">
                            <el-input v-model="currentUser.original_transaction_id" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="当前订单ID">
                            <el-input v-model="currentUser.transaction_id" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="订阅开始时间">
                            <el-input v-model="currentUser.subscription_start_date" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="订阅过期时间">
                            <el-input v-model="currentUser.subscription_expiry_date" disabled />
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="8">
                        <el-form-item label="赠送天数">
                            <el-input v-model="currentUser.bonus_days" disabled />
                        </el-form-item>
                    </el-col> -->
                </el-row>

                <!-- 邀请信息 -->
                <el-divider>邀请信息</el-divider>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="邀请码">
                            <el-input v-model="currentUser.invitation_code" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="已邀请人数">
                            <el-input v-model="currentUser.invited_count" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="邀请奖励待兑换天数">
                            <el-input v-model="currentUser.invite_reward_pending_days" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="已兑换的邀请奖励天数">
                            <el-input v-model="currentUser.invite_reward_redeemed_days" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="会员过期后待生效的临时会员天数">
                            <el-input v-model="currentUser.post_vip_pending_days" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="邀请人ID">
                            <el-input v-model="currentUser.invited_by" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="邀请人名字">
                            <el-input v-model="currentUser.inviter_name" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="被邀请时间">
                            <el-input v-model="currentUser.invitation_time" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 个人信息 -->
                <el-divider>个人信息</el-divider>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="性别">
                            <el-input v-model="currentUser.gender" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="出生年月">
                            <el-input v-model="currentUser.birth_date" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="星座">
                            <el-input v-model="currentUser.zodiac_sign" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">

                    <el-col :span="8">
                        <el-form-item label="国家">
                            <el-input v-model="currentUser.country" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="城市">
                            <el-input v-model="currentUser.city" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">

                    <el-col :span="24">
                        <el-form-item label="喜好标签">
                            <el-input :value="mapInterestsToChinese(currentUser.interests)" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 功能使用情况 -->
                <el-divider>功能使用情况</el-divider>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="功能是否使用过">
                            <el-input v-model="currentUser.feature_used" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showDialog = false">关闭</el-button>
            </span>
        </el-dialog>

        <!-- 自定义肯定语弹窗 -->
        <el-dialog title="自定义肯定语" :visible.sync="showUserAffirmationsDialog" width="900px"
            @close="closeAffirmationsDialog">
            <el-table :data="userAffirmationsList" border v-loading="dialogLoading" size="small">
                <el-table-column prop="language" label="语言" width="80" />
                <el-table-column prop="theme" label="主题">
                    <template slot-scope="scope">
                        {{ themeMap[scope.row.theme] || scope.row.theme }}
                    </template>
                </el-table-column>
                <el-table-column prop="moon_phase" label="月相" />
                <el-table-column prop="sentence" label="肯定语" show-overflow-tooltip width="350" />
                <el-table-column prop="universe_reply" label="宇宙回应" show-overflow-tooltip width="200" />
                <el-table-column prop="created_at" label="创建时间" width="160" />
            </el-table>
            <el-pagination class="pagination" @current-change="handleAffirmationsPageChange"
                :current-page="affirmationsPage" :page-size="affirmationsPageSize"
                layout="total, prev, pager, next, jumper" :total="affirmationsTotal" />
            <span slot="footer" class="dialog-footer">
                <el-button @click="showUserAffirmationsDialog = false">关闭</el-button>
            </span>
        </el-dialog>

        <!-- 收藏肯定语弹窗 -->
        <el-dialog title="收藏肯定语" :visible.sync="showFavoritesDialog" width="900px" @close="closeFavoritesDialog">
            <el-table :data="favoritesAffirmationsList" border v-loading="dialogLoading" size="small">
                <el-table-column prop="sentence" label="肯定语" show-overflow-tooltip width="400" />
                <el-table-column prop="theme" label="主题">
                    <template slot-scope="scope">
                        {{ themeMap[scope.row.theme] || scope.row.theme }}
                    </template>
                </el-table-column>
                <el-table-column prop="language" label="语言" width="80" />
                <el-table-column prop="moon_phase" label="月相" />
                <el-table-column prop="created_at" label="收藏时间" width="160" />
            </el-table>
            <el-pagination class="pagination" @current-change="handleFavoritesPageChange" :current-page="favoritesPage"
                :page-size="favoritesPageSize" layout="total, prev, pager, next, jumper" :total="favoritesTotal" />
            <span slot="footer" class="dialog-footer">
                <el-button @click="showFavoritesDialog = false">关闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import axios from 'axios'

export default {
    name: "tarot-user-list",
    data() {
        return {
            queryParams: {
                username: "",
                user_type: "",
                country: "",
                city: "",
                gender: "",
                registration_time_range: {
                    start: "",
                    end: "",
                },
                page: 1,
                size: 10,
            },
            userList: [],
            total: 0,
            loading: false,
            showDialog: false,
            currentUser: {},
            value1: "",
            countryOptions: [], // 国家选项
            showInvitationDialog: false,
            invitationList: [],
            invitationPage: 1,
            invitationPageSize: 10,
            invitationTotal: 0,
            showActiveDialog: false,
            activeList: [],
            activePage: 1,
            activePageSize: 10,
            activeTotal: 0,
            dialogLoading: false,
            showUserAffirmationsDialog: false,
            userAffirmationsList: [],
            affirmationsPage: 1,
            affirmationsPageSize: 10,
            affirmationsTotal: 0,

            showFavoritesDialog: false,
            favoritesAffirmationsList: [],
            favoritesPage: 1,
            favoritesPageSize: 10,
            favoritesTotal: 0,
            themeMap : {
                "wealth": "财富",
                "tough_times": "艰难时刻",
                "social_interaction": "人际交往",
                "beauty_and_image": "美丽与形象",
                "self_care": "自我关怀",
                "health_focus": "关注健康",
                "romance": "浪漫关系",
                "self_growth": "自我成长",
                "career_and_growth": "事业与发展",
                "healing_journey": "治愈之旅",
                "gratitude": "感恩与欣赏",
                "relaxation": "放松与解压",
                "comprehensive": "综合"
            }
        };
    },
    created() {
        this.fetchCountryList();
        this.getUsers();
    },
    methods: {
        
        mapInterestsToChinese(interestsStr) {
            const interestMapReverse = {
                "wealth": "财富",
                "tough_times": "艰难时刻",
                "social_interaction": "人际交往",
                "beauty_and_image": "美丽与形象",
                "self_care": "自我关怀",
                "health_focus": "关注健康",
                "romance": "浪漫关系",
                "self_growth": "自我成长",
                "career_and_growth": "事业与发展",
                "healing_journey": "治愈之旅",
                "gratitude": "感恩与欣赏",
                "relaxation": "放松与解压",
                "comprehensive": "综合"
            };
            if (!interestsStr) return '';
            return interestsStr
                .split(',')
                .map(key => interestMapReverse[key.trim()] || key.trim())
                .join('，');
        },
        async fetchCountryList() {
            this.loading = true;
            try {
                const res = await axios.get("https://xiaoshuchengzhang.com/node/Tarot/countries");
                if (res.data.code === 0) {
                    this.countryOptions = res.data.data || [];
                }
            } catch (e) {
                this.$message.error("获取国家列表失败");
            }
            this.loading = false;
        },
        async getUsers() {
            this.loading = true;
            try {
                const params = {
                    ...this.queryParams,
                    registration_time_start: this.queryParams.registration_time_range.start,
                    registration_time_end: this.queryParams.registration_time_range.end,
                };
                const res = await axios.post("https://xiaoshuchengzhang.com/node/Tarot/tarot-users/list", params);
                if (res.data.code === 0) {
                    this.userList = res.data.data.listWithFormatTime || [];
                    this.total = res.data.data.total || 0;
                } else {
                    this.$message.error(res.data.msg || "获取用户数据失败");
                }
            } catch (e) {
                this.$message.error("网络异常！");
            }
            this.loading = false;
        },
        handleQuery() {
            this.queryParams.page = 1;
            this.getUsers();
        },
        resetQuery() {
            this.queryParams = {
                username: "",
                user_type: "",
                country: "",
                city: "",
                gender: "",
                registration_time_range: {
                    start: "",
                    end: "",
                },
                page: 1,
                size: 10,
            };
            this.value1 = "";
            this.getUsers();
        },
        timeChange() {
            if (this.value1) {
                this.queryParams.registration_time_range.start = this.value1[0];
                this.queryParams.registration_time_range.end = this.value1[1];
            } else {
                this.queryParams.registration_time_range.start = "";
                this.queryParams.registration_time_range.end = "";
            }
            this.handleQuery();
        },
        handleSizeChange(size) {
            this.queryParams.size = size;
            this.queryParams.page = 1;
            this.getUsers();
        },
        handleCurrentChange(page) {
            this.queryParams.page = page;
            this.getUsers();
        },
        showDetail(row) {
            this.currentUser = { ...row };
            this.showDialog = true;
        },
        async showInvitationRecords(row) {
            this.currentUserId = row.user_id;
            this.invitationPage = 1;
            await this.getInvitationRecords();
            this.showInvitationDialog = true;
        },
        async getInvitationRecords() {
            this.dialogLoading = true;
            try {
                const params = {
                    user_id: this.currentUserId,
                    page: this.invitationPage,
                    page_size: this.invitationPageSize,
                };
                const res = await axios.get("https://xiaoshuchengzhang.com/node/Tarot/tarot-users/invitations", { params });
                if (res.data.code === 0) {
                    const { list, total } = res.data.data;
                    this.invitationList = list;
                    this.invitationTotal = total;
                } else {
                    this.$message.error(res.data.msg || "获取邀请记录失败");
                }
            } catch (e) {
                this.$message.error("网络异常！");
            }
            this.dialogLoading = false;
        },
        handleInvitationPageChange(page) {
            this.invitationPage = page;
            this.getInvitationRecords();
        },
        closeInvitationDialog() {
            this.showInvitationDialog = false;
            this.invitationList = [];
            this.currentUserId = null;
            this.invitationPage = 1;
        },
        async showActiveRecords(row) {
            this.currentUserId = row.user_id;
            this.activePage = 1;
            await this.getActiveRecords();
            this.showActiveDialog = true;
        },
        async getActiveRecords() {
            this.dialogLoading = true;
            try {
                const params = {
                    user_id: this.currentUserId,
                    page: this.activePage,
                    page_size: this.activePageSize,
                };
                const res = await axios.get("https://xiaoshuchengzhang.com/node/Tarot/tarot-users/active-records", { params });
                if (res.data.code === 0) {
                    const { list, total } = res.data.data;
                    this.activeList = list;
                    this.activeTotal = total;
                } else {
                    this.$message.error(res.data.msg || "获取活跃记录失败");
                }
            } catch (e) {
                this.$message.error("网络异常！");
            }
            this.dialogLoading = false;
        },
        handleActivePageChange(page) {
            this.activePage = page;
            this.getActiveRecords();
        },
        closeActiveDialog() {
            this.showActiveDialog = false;
            this.activeList = [];
            this.currentUserId = null;
            this.activePage = 1;
        },
        async showActiveRecords(row) {
            this.currentUserId = row.user_id;
            this.activePage = 1;
            await this.getActiveRecords();
            this.showActiveDialog = true;
        },
        async getActiveRecords() {
            this.dialogLoading = true;
            try {
                const params = {
                    user_id: this.currentUserId,
                    page: this.activePage,
                    page_size: this.activePageSize,
                };
                const res = await axios.get("https://xiaoshuchengzhang.com/node/Tarot/tarot-users/active-records", { params });
                if (res.data.code === 0) {
                    const { list, total } = res.data.data;
                    this.activeList = list;
                    this.activeTotal = total;
                } else {
                    this.$message.error(res.data.msg || "获取活跃记录失败");
                }
            } catch (e) {
                this.$message.error("网络异常！");
            }
            this.dialogLoading = false;
        },
        handleActivePageChange(page) {
            this.activePage = page;
            this.getActiveRecords();
        },
        closeActiveDialog() {
            this.showActiveDialog = false;
            this.activeList = [];
            this.currentUserId = null;
            this.activePage = 1;
        },
        async showUserAffirmations(row) {
            this.currentUserId = row.user_id;
            this.affirmationsPage = 1;
            await this.getUserAffirmations();
            this.showUserAffirmationsDialog = true;
        },
        async getUserAffirmations() {
            this.dialogLoading = true;
            try {
                const params = {
                    user_id: this.currentUserId,
                    page: this.affirmationsPage,
                    page_size: this.affirmationsPageSize,
                };
                // 后端接口
                const res = await axios.get("https://xiaoshuchengzhang.com/node/Tarot/user-affirmations/list", { params });
                if (res.data.code === 0) {
                    this.userAffirmationsList = res.data.data.list;
                    this.affirmationsTotal = res.data.data.total;
                } else {
                    this.$message.error(res.data.msg || "获取自定义肯定语失败");
                }
            } catch (e) {
                this.$message.error("网络异常！");
            }
            this.dialogLoading = false;
        },
        handleAffirmationsPageChange(page) {
            this.affirmationsPage = page;
            this.getUserAffirmations();
        },
        closeAffirmationsDialog() {
            this.showUserAffirmationsDialog = false;
            this.userAffirmationsList = [];
            this.currentUserId = null;
            this.affirmationsPage = 1;
        },

        async showFavoritesAffirmations(row) {
            this.currentUserId = row.user_id;
            this.favoritesPage = 1;
            await this.getFavoritesAffirmations();
            this.showFavoritesDialog = true;
        },
        async getFavoritesAffirmations() {
            this.dialogLoading = true;
            try {
                const params = {
                    user_id: this.currentUserId,
                    page: this.favoritesPage,
                    page_size: this.favoritesPageSize,
                };
                const res = await axios.get("https://xiaoshuchengzhang.com/node/Tarot/user-affirmations/favorites", { params });
                if (res.data.code === 0) {
                    this.favoritesAffirmationsList = res.data.data.list;
                    this.favoritesTotal = res.data.data.total;
                } else {
                    this.$message.error(res.data.msg || "获取收藏肯定语失败");
                }
            } catch (e) {
                this.$message.error("网络异常！");
            }
            this.dialogLoading = false;
        },
        handleFavoritesPageChange(page) {
            this.favoritesPage = page;
            this.getFavoritesAffirmations();
        },
        closeFavoritesDialog() {
            this.showFavoritesDialog = false;
            this.favoritesAffirmationsList = [];
            this.currentUserId = null;
            this.favoritesPage = 1;
        },

    },
};
</script>
<style scoped>
.user-list-wrapper {
    padding: 18px 8px 32px 8px;
    background: #f7f7f7;
    min-height: 90vh;
}

.mb-2 {
    margin-bottom: 18px;
}

.pagination {
    margin: 18px auto 0 auto;
    text-align: right;
}

::v-deep .el-input.is-disabled .el-input__inner {
    color: #333;
}
</style>
